<template>
  <Modal v-model="modal" :title="title" :styles="styles">
    <template v-if="identifyStatus == 'CERTIFICATION_REVIEW'">
      <div class="tag-modal h400 scroll" >
        <p>{{realname}}属于{{distributorName}}，已有{{verifiedBossCount + unverifiedBossCount}}名已认证老板，已有{{salesmanCount}}名认证经销商业务员，{{managerCount}}名认证经销商经理，{{backOfficeCount}}名认证经销商内勤</p>
        <Form :model="form" :label-width="100" ref="form" :rules="rules" key="ident">
          <FormItem label="身份证正面">
            <a :href="form.idCardPositivePic" target="_blank"><img :src="form.idCardPositivePic" style="width: 300px;"/></a>
          </FormItem>
          <FormItem label="身份证反面">
            <a :href="form.idCardNegativePic" target="_blank"><img :src="form.idCardNegativePic" style="width: 300px;"/></a>
          </FormItem>
          <FormItem label="认证身份号:">
            <p>{{form.idCardNo}}</p>
          </FormItem>
          <FormItem label="身份证有效期:" :label-width="110">
            <p>{{idCardValidity}}</p>
          </FormItem>
          <FormItem label="认证品牌:">
            <p>{{form.brandName}}</p>
          </FormItem>
          <FormItem label="认证职能:">
            <p>{{form.functionType | filteFunctionTypeList}}</p>
          </FormItem>
          <FormItem label="认证状态:">
            <p>认证审核中</p>
            <Input maxlength="100" show-word-limit type="textarea" placeholder="认证审核意见，审核不通过必填" v-model="form.auditRemark"/>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button :disabled="btnDisabled" @click="onOk" type="primary" size="large">审核通过</Button>
        <Button :disabled="btnDisabled" @click="onRefuse" size="large">审核不通过</Button>
        <Button @click="cancel" size="large" type="text">取消</Button>
      </div>
    </template>
    <template v-else>
      <div class="tag-modal">
        <p>{{realname}}属于{{distributorName}}，已有{{verifiedBossCount + unverifiedBossCount}}名已认证老板，已有{{salesmanCount}}名认证经销商业务员，{{managerCount}}名认证经销商经理，{{backOfficeCount}}名认证经销商内勤</p>
        <Form :model="form" :label-width="100" ref="form" :rules="rules" key="edit">
          <FormItem label="身份证正面" prop="idCardPositivePic">
            <Input v-model="form.idCardPositivePic" v-show="false"/>
            <PictureEditItem 
              :uploadList="uploadListProtraitPhoto" 
              :maxlength="1" 
              @uploadPic="uploadPic"></PictureEditItem>
          </FormItem>
          <FormItem label="身份证反面" prop="idCardNegativePic">
            <Input v-model="form.idCardNegativePic" v-show="false"/>
            <PictureEditItem 
              :uploadList="uploadListReversePhoto" 
              :maxlength="1" 
              @uploadPic="uploadPicReverse"></PictureEditItem>
          </FormItem>
          <FormItem label="认证身份号:" prop="idCardNo">
            <Input v-model="form.idCardNo" placeholder=""/>
          </FormItem>
          <FormItem label="身份证有效期:" :label-width="110" prop="idCardValidity">
            <DatePicker type="date" placeholder="" v-model="form.idCardValidity"></DatePicker>
          </FormItem>
          <FormItem label="认证品牌:" prop="brandId">
            <RadioGroup v-model="form.brandId">
              <Radio 
                v-for="item in brandList" 
                :key="item.id"
                :label="item.id">
                <span>{{item.name}}</span>
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="认证职能:" prop="functionType">
            <RadioGroup v-model="form.functionType">
              <Radio 
                v-for="item in functionTypeList" 
                :key="item.id"
                :label="item.enum">
                <span>{{item.name}}</span>
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="认证状态:" prop="identifyStatus">
            <RadioGroup v-model="form.identifyStatus">
              <Radio 
                v-for="item in identifyStatusList" 
                :key="item.id"
                :label="item.enum">
                <span>{{item.name}}</span>
              </Radio>
            </RadioGroup>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button :disabled="btnDisabled" @click="onSave" type="primary" size="large">确定</Button>
        <Button @click="cancel" size="large" type="text">取消</Button>
      </div>
    </template>
    <Loader :status="status" @refresh="getData"></Loader>
  </Modal>
</template>
<script>
import { idCardReg, formatDate } from '@/util'
import PictureEditItem from '@/components/PictureEditItem'
export default {
  components: {
    PictureEditItem
  },
  data() {
    const validateCard = (rule, value, callback) => {
      if (value) {
        if (!idCardReg.test(value.trim())) {
          this.disabled = true
          callback(new Error('身份证格式不正确'))
        } else {
          this.disabled = false
          callback()
        }
      } else {
        callback(new Error('请输入身份证号码'))
      }
    }
    return {
      styles: {
        height: '700px',
        overflow: 'auto'
      },
      modalFlag: 'right',
      id: null,
      distributorId: null,
      identifyStatus: null,
      modal: false,
      title: '',
      idCardValidity: '',
      managerCount: '', //认证经销商经理
      salesmanCount: '', //认证经销商业务员
      backOfficeCount: '', //认证经销商内勤
      distributorName: '', //xxx
      realname: '', //业务员,
      bossCount: '',
      status: 'pass',
      form: {
        idCardNo: null,
        functionType: null,
        identifyStatus: null,
        brandId: '',
        id: null,
        idCardNegativePic: '', //反面
        idCardPositivePic: '', //正面
        idCardValidity: '',
        auditRemark: null
      },
      brandList: [], //认证品牌
      functionTypeList: [], //认证职能
      identifyStatusList: [], //认证状态
      rules: {
        idCardPositivePic: [
          {
            required: true,
            message: '请上传身份证正面',
            trigger: 'blur'
          }
        ],
        idCardNegativePic: [
          {
            required: true,
            message: '请上传身份证反面',
            trigger: 'blur'
          }
        ],
        idCardValidity: [
          { 
            required: true,
            type: 'date',
            message: '请输入身份证有效期',
            trigger: 'change'
          }
        ],
        brandId: [
          {
            required: true,
            message: '请选择认证品牌',
            trigger: 'change'
          }
        ],
        functionType: [
          {
            required: true,
            message: '请选择认证职能',
            trigger: 'change'
          }
        ],
        identifyStatus: [
          {
            required: true,
            message: '请选择认证状态',
            trigger: 'change'
          }
        ],
        idCardNo: [
          {
            required: true,
            validator: validateCard,
            trigger: 'blur'
          }
        ]
      },
      btnDisabled: false,
      flag: false,
      uploadListProtraitPhoto: [],
      uploadListReversePhoto: []
    }
  },
  methods: {
    resetForm() {
      // this.$refs.form.resetFields()
      this.form = {
        idCardNo: null,
        functionType: null,
        identifyStatus: null,
        brandId: null,
        idCardNegativePic: '', //反面
        idCardPositivePic: '', //正面
        idCardValidity: '',
        brandName: ''
      },
      this.modalFlag = 'right'
      this.uploadListProtraitPhoto = []
      this.uploadListReversePhoto = []
      this.btnDisabled = false
    },
    updateForm(row) {
      this.resetForm()
      if (row) {
        this.id = row.salesmanId
        this.distributorId = row.distributorId
        this.identifyStatus = row.identifyStatus
        this.title = this.identifyStatus == 'CERTIFICATION_REVIEW' ? '认证审核' : '认证编辑'
        this.getData().then(() => {
          if (this.modalFlag === 'right') {
            this.openModal()
          }
        })
      }
    },
    openModal() {
      this.btnDisabled = false
      this.modal = true
    },
    onCancel() {
      // this.$refs["form"].resetFields()
      this.modal = false
    },
    cancel() {
      // this.$refs["form"].resetFields()
      this.modal = false
    },
    uploadPic(val) {
      this.form.idCardPositivePic = val.length > 0 ? val[0].url.urlPrefix + val[0].imgUrl : ''
    },
    uploadPicReverse(val) {
      this.form.idCardNegativePic = val.length > 0 ? val[0].url.urlPrefix + val[0].imgUrl : ''
    },
    async getData() {
      // let url = this.identifyStatus == 'CERTIFICATION_REVIEW' ? `/salesman/identify_apply/detail/${this.id}` : `/salesman/identify/detail/${this.id}`
      let url = this.identifyStatus == 'CERTIFICATION_REVIEW' ? `/salesman/identify_apply/detail` : `/salesman/identify/detail`
      this.status = 'loading'
      let params = {
        distributorId: this.distributorId,
        salesmanId: this.id
      }
      await this.$jsonPost(url, params).then(data => {
        if (data) {
          this.distributorName = data.salesmanIdentify.distributorName
          this.realname = data.salesmanIdentify.realname
          this.managerCount = data.managerCount
          this.salesmanCount = data.salesmanCount
          this.backOfficeCount = data.backOfficeCount
          this.verifiedBossCount = data.verifiedBossCount
          this.unverifiedBossCount = data.unverifiedBossCount
          this.form = {
            idCardNo: data.salesmanIdentify.idCardNo,
            functionType: data.salesmanIdentify.functionType ? data.salesmanIdentify.functionType.toString() : '',
            identifyStatus: data.salesmanIdentify.identifyStatus ? data.salesmanIdentify.identifyStatus.toString() : '',
            brandId: data.salesmanIdentify.brandId ? data.salesmanIdentify.brandId.toString() : '',
            brandName: data.salesmanIdentify.brandName,
            id: data.salesmanIdentify.id,
            idCardValidity: data.salesmanIdentify.idCardValidity,
            idCardPositivePic: data.salesmanIdentify.idCardPositivePic,
            idCardNegativePic: data.salesmanIdentify.idCardNegativePic
          }
          this.idCardValidity = formatDate(this.form.idCardValidity)
          this.uploadListProtraitPhoto = data.salesmanIdentify.idCardPositivePic ? [{
            imgUrl: data.salesmanIdentify.idCardPositivePic,
            status: 'finished'
          }] : []
          this.uploadListReversePhoto = data.salesmanIdentify.idCardNegativePic ? [{
            imgUrl: data.salesmanIdentify.idCardNegativePic,
            status: 'finished'
          }] : []
          this.brandList = (data.brandList || []).map(item => {
            return {
              id: item.brandId,
              name: item.brandName
            }
          })
          this.functionTypeList = (data.functionTypeList || []).map(item => {
            return {
              id: item.value.toString(),
              name: item.name,
              enum: item.enum
            }
          })
          let arr = data.identifyStatusList.filter((item) =>  {
              return item.value > 0
          })
          this.identifyStatusList = arr.map(item => {
            return {
              id: item.value.toString(),
              name: item.name,
              enum: item.enum
            }
          })
          this.status = 'pass'
        }
        this.modalFlag = 'right'
      }).catch(()=> {
        this.status = 'error'
        this.modalFlag = 'error'
      })
    },
    onSave() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.btnDisabled) return
          // if (this.form.functionType == 'SALESMAN') {
          //   this.$Notice.error({
          //     title: '提示',
          //     desc: '该业务员没有维护任何有效门店，是否确认职能类型为经销商业务员?'
          //   })
          //   return
          // }
          this.btnDisabled = true
          let param = {
            idCardNo: this.form.idCardNo,
            functionType: this.form.functionType,
            identifyStatus: this.form.identifyStatus,
            brandId: this.form.brandId,
            id: this.form.id,
            idCardNegativePic: this.form.idCardNegativePic, //反面
            idCardPositivePic: this.form.idCardPositivePic, //正面
            idCardValidity: formatDate(this.form.idCardValidity) + ' 00:00:00'
          }
          let url = '/salesman/identify/update'
          this.$jsonPost(url, param).then(data => {
            this.btnDisabled = false
            this.$Notice.success({
              title: '修改成功'
            })
            this.$emit('complete')
            this.onCancel()
          }).catch(() => {
            this.btnDisabled = false
            // this.$Notice.error({
            //   title: '修改失败'
            // })
          })
        }
      })
    },
    onOk () {
      if (this.btnDisabled) return
      this.btnDisabled = true
      let param = {
        // auditRemark: this.form.auditRemark,
        auditStatus: 2, // 审核通过
        distributorId: this.distributorId,
        salesmanId: this.id
      }
      let url = '/salesman/identify_apply/audit'
      this.$jsonPost(url, param).then(data => {
        this.btnDisabled = false
        this.$Notice.success({
          title: '审核成功'
        })
        this.$emit('complete')
        this.onCancel()
      }).catch(() => {
        this.btnDisabled = false
        // this.$Notice.error({
        //   title: '审核失败'
        // })
      })
    },
    onRefuse() {
      if (this.btnDisabled) return
      this.btnDisabled = true
      if (this.form.auditRemark) {
        let param = {
          auditRemark: this.form.auditRemark,
          auditStatus: 1, // 审核不通过
          distributorId: this.distributorId,
          salesmanId: this.id
        }
        let url = '/salesman/identify_apply/audit'
        this.$jsonPost(url, param).then(data => {
          this.btnDisabled = false
          this.$Notice.success({
            title: '审核不通过成功'
          })
          this.$emit('complete')
          this.onCancel()
        }).catch(() => {
          this.btnDisabled = false
          // this.$Notice.error({
          //   title: '审核不通过失败'
          // })
        })
      } else {
        this.btnDisabled = false
        this.$Notice.error({
          title: '审核意见必填'
        })
      }
    }
  },
  filters: {
    filteFunctionTypeList(value) {
      let list = {
        'BOSS': '老板',
        'MANAGER': '经销商经理',
        'SALESMAN': '经销商业务员',
        'BACK_OFFICE': '经销商内勤'
      }
      return list[value]
    }
  }
}
</script>